package org.fao.oekc.agris.inputRecords.util;

import java.net.MalformedURLException;

import org.apache.solr.client.solrj.SolrServerException;
import org.fao.oekc.agris.index.IndexServerFactory;
import org.fao.oekc.agris.index.QueryUtil;

/**
 * Manage ARN, i.e. uniqueness, check existence...
 * @author celli
 *
 */
public class ArnManager {
	
	/**
	 * Given an ARN prefix, extract from the index the last assigned ID as last 5 ARN chars, to compute the new usable ID
	 * @param arnPrefix the ARN prefix
	 * @return the new usable ID as last 5 ARN chars
	 */
	public int getMaxArnCode(String arnPrefix){
		//look for last ID number
		int startId = 0;
		try {
			String maxARN = QueryUtil.selectMaxValue(IndexServerFactory.startSolr(), "ARN:"+arnPrefix+"*", "ARN");
			if(maxARN!=null && maxARN.length()>0){
				//take last 5 chars
				if(maxARN.length()>5) {
					maxARN = maxARN.substring(maxARN.length()-5, maxARN.length());
					startId = Integer.parseInt(maxARN);
					startId = startId+1;
				}
			}
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (SolrServerException e1) {
			e1.printStackTrace();
		}
		//String arn = arnprefix+StringCleaning.formatInteger(startArnIdNumber,5);
		return startId;
	}

}
